// Dropdown.tsx
import React, { useState, useRef, useEffect } from "react";
import "./Dropdown.scss";

export interface DropdownOption {
  label?: string;
  name?: string;
  value?: any;
  _id?: any;
}

export interface DropdownProps {
  options: DropdownOption[];
  value?: any;
  onChange?: (value: any) => void;
  placeholder?: string;
  className?: String;
}

const Dropdown: React.FC<DropdownProps> = ({
  options, //选项参数
  value, // 绑定
  onChange, // 回调
  placeholder = "请选择~", //默认显示
  className, // 自定义样式
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const wrapperRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (
        wrapperRef.current &&
        !wrapperRef.current.contains(event.target as Node)
      ) {
        setIsOpen(false);
      }
    }
    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);

  const handleItemClick = (optionValue: any) => {
    if (onChange) {
      onChange(optionValue);
    }
    setIsOpen(false);
  };
  return (
    <div className={`dropdown ${className}`} ref={wrapperRef}>
      <div className="dropdown-header" onClick={() => setIsOpen(!isOpen)}>
        {value
          ? options.find((option) => option._id === value)?.name
          : placeholder}
        <span
          className={`dropdown-caret ${isOpen ? "dropdown-caret--open" : ""}`}
        />
      </div>
      {isOpen && (
        <ul className="dropdown-list">
          {options.map((option) => (
            <li
              key={option.name ? option.name : option.label}
              className="dropdown-item"
              onClick={() => handleItemClick(option)}
            >
              {option.name ? option.name : option.label}
            </li>
          ))}
        </ul>
      )}
    </div>
  );
};

export default Dropdown;
